package com.lpf;

import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.compiler.Compiler;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.registry.RegistryFactory;
import org.apache.dubbo.remoting.Transporter;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Protocol;
import org.apache.dubbo.rpc.ProxyFactory;

import java.util.List;

/**
 * dubbo spi 机制
 */
public class DubooSPIDemo {

    public static void main(String[] args) {

        /**
         * 静态扩展点：
         *      1. load指定路径下对应SPI扩展点的实现，缓存到hashmap，key对应的就是文件中定义的key，value就是class
         *      2. getExtension("name") -> EXTENSION_INSTANCES.get("name")
         */
        Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getExtension("myprotocol");
        System.out.println(protocol.getDefaultPort());

        Protocol registry = ExtensionLoader.getExtensionLoader(Protocol.class).getExtension("registry");
        Protocol dubbo = ExtensionLoader.getExtensionLoader(Protocol.class).getExtension("dubbo");

        /**
         * 自适应扩展点：
         * 输出：org.apache.dubbo.common.compiler.support.AdaptiveCompiler@555590
         *
         * 方法上的为动态生成代理，类上的有已经写好的自适应扩展点
         */
        // 类上
        Compiler compiler = ExtensionLoader.getExtensionLoader(Compiler.class).getAdaptiveExtension();
        System.out.println(compiler);

        // 方法上
        Transporter transporter = ExtensionLoader.getExtensionLoader(Transporter.class).getAdaptiveExtension();
        System.out.println(transporter);

        // 方法上
        ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension();
        System.out.println(proxyFactory);

        ProxyFactory javassist = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getExtension("javassist");
        System.out.println(javassist);

        // 方法上
        RegistryFactory registryFactory = ExtensionLoader.getExtensionLoader(RegistryFactory.class).getAdaptiveExtension();
        System.out.println(registryFactory);


        /**
         *  激活扩展点：
         */
        URL url = new URL("", "", 0);
         url = url.addParameter("cache1", "cache");
        // url = url.addParameter("cache1", "activelimit");
        List<Filter> list = ExtensionLoader.getExtensionLoader(Filter.class).getActivateExtension(url, "cache1");
        System.out.println(list.size());

    }
}
